<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传聊天框</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body, html {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            background-color: white;
            position: relative;
            overflow: hidden;
        }

        .main-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            padding-top: 15vh;
            flex: 1;
            overflow-y: auto;
            padding-bottom: 20px;
        }

        .upload-btn {
            background-color: #3a6bc8;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 20px 40px;
            font-size: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            min-width: 280px;
            margin-bottom: 20px;
            position: relative;
        }

        .upload-btn:hover {
            background-color: #2c5bb4;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }

        .upload-btn-icons {
            display: none;
            margin-left: 10px;
            gap: 8px;
        }

        .upload-btn-icons i {
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .upload-btn-icons i:hover {
            transform: scale(1.1);
        }

        .upload-btn-icons .fa-paper-plane:hover {
            color: #2ecc71;
        }

        .upload-btn-icons .fa-trash-alt:hover {
            color: #e74c3c;
        }

        .file-input {
            display: none;
        }

        .messages-container {
            width: 100%;
            max-width: 600px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .success-message {
            color: #3a6bc8;
            font-size: 14px;
            margin: 10px 0;
            text-align: center;
            display: none;
            animation: messageAppear 0.3s ease-out;
        }

        .training-message {
            color: #6a5acd;
            font-size: 14px;
            margin: 5px 0 15px 0;
            text-align: center;
            display: none;
        }

        .next-btn {
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 24px;
            margin: 15px 0;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
        }

        .next-btn:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .next-btn:hover:not(:disabled) {
            background-color: #27ae60;
        }

        .parameter-input-container {
            width: 350px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            margin: 15px 0;
            display: none;
            animation: messageAppear 0.5s ease-out;
        }

        .parameter-item {
            margin-bottom: 15px;
        }

        .parameter-label {
            font-weight: bold;
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-size: 15px;
        }

        .parameter-input {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 100%;
            font-size: 15px;
        }

        .parameter-input:focus {
            outline: none;
            border-color: #3a6bc8;
            box-shadow: 0 0 0 2px rgba(58, 107, 200, 0.2);
        }

        .system-message {
            color: #0066cc;
            margin: 10px 0;
            text-align: center;
            max-width: 80%;
            padding: 0;
            font-size: 14px;
            line-height: 1.5;
            animation: messageAppear 0.3s ease-out;
        }

        .param-next-btn-container {
            text-align: center;
            margin-top: 20px;
        }

        .button-group {
            display: flex;
            gap: 15px;
            align-items: center;
            justify-content: center;
            margin-top: 15px;
        }

        .reupload-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 24px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            display: none;
        }

        .reupload-btn:hover {
            background-color: #c0392b;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="main-content" id="mainContent">
        <button class="upload-btn" id="uploadBtn">
            <i class="fas fa-paperclip"></i>
            <span id="uploadBtnText">上传训练文件</span>
            <span class="upload-btn-icons" id="uploadBtnIcons">
                    <i class="fas fa-paper-plane" id="sendIcon" title="上传文件"></i>
                    <i class="fas fa-trash-alt" id="trashIcon" title="取消选择"></i>
                </span>
        </button>
        <input type="file" id="fileInput" class="file-input" accept=".csv,.txt,.json">

        <div class="messages-container" id="messagesContainer">
            <!-- 动态消息将在这里显示 -->
        </div>

        <div class="button-group" id="buttonGroup">
            <button class="reupload-btn" id="reuploadBtn">
                <i class="fas fa-redo"></i> 重新上传文件
            </button>
            <button class="next-btn" id="nextBtn" style="display: none;">下一步</button>
        </div>

        <div class="parameter-input-container" id="parameterContainer">
            <div class="parameter-item" id="param1">
                <label class="parameter-label" for="paramInput1">训练轮数</label>
                <input type="text" class="parameter-input" id="paramInput1" placeholder="例如: 40">
            </div>
            <div class="parameter-item" id="param2">
                <label class="parameter-label" for="paramInput2">批次比例大小</label>
                <input type="text" class="parameter-input" id="paramInput2" placeholder="例如: 0.3">
            </div>
            <div class="parameter-item" id="param3">
                <label class="parameter-label" for="paramInput3">序列长度</label>
                <input type="text" class="parameter-input" id="paramInput3" placeholder="例如: 20">
            </div>
            <!-- 新增学习率参数 -->
            <div class="parameter-item" id="param4">
                <label class="parameter-label" for="paramInput4">学习率</label>
                <input type="text" class="parameter-input" id="paramInput4" placeholder="例如: 0.001">
            </div>
            <div class="param-next-btn-container">
                <button class="next-btn" id="paramNextBtn" disabled>下一步</button>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadBtnText = document.getElementById('uploadBtnText');
        const uploadBtnIcons = document.getElementById('uploadBtnIcons');
        const sendIcon = document.getElementById('sendIcon');
        const trashIcon = document.getElementById('trashIcon');
        const fileInput = document.getElementById('fileInput');
        const messagesContainer = document.getElementById('messagesContainer');
        const nextBtn = document.getElementById('nextBtn');
        const reuploadBtn = document.getElementById('reuploadBtn');
        const buttonGroup = document.getElementById('buttonGroup');
        const parameterContainer = document.getElementById('parameterContainer');
        const paramNextBtn = document.getElementById('paramNextBtn');
        const paramInput1 = document.getElementById('paramInput1');
        const paramInput2 = document.getElementById('paramInput2');
        const paramInput3 = document.getElementById('paramInput3');
        const paramInput4 = document.getElementById('paramInput4');


        const paramInputs = [paramInput1, paramInput2, paramInput3, paramInput4];

        let selectedFile = null;

        // 建立WebSocket连接
        const socket = new WebSocket('ws://' + window.location.host + '/ws/train/');
        const trainResultSocket = new WebSocket('ws://' + window.location.host + '/ws/training-results/?page=chat');  // 修改WebSocket端点

        // WebSocket事件监听
        socket.onopen = function(e) {
            console.log('WebSocket连接已建立');
            addSystemMessage('服务器连接成功');
        };

        socket.onerror = function(error) {
            console.error('WebSocket错误:', error);
            addSystemMessage('连接发生错误');
        };

        socket.onclose = function(e) {
            console.log('连接关闭');
            addSystemMessage('连接断开，请刷新页面');
        };

        socket.onmessage = function(e) {
            console.log('收到服务器消息:', e.data);
            const data = JSON.parse(e.data);

            if (data.type === 'status') {
                addSystemMessage(data.message);
            } else if (data.type === 'error') {
                addSystemMessage('错误: ' + data.message);
            }
        };

        // 辅助函数
        function addSystemMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'system-message';
            messageDiv.textContent = text;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function checkParametersFilled() {
            const allFilled = paramInputs.every(input => input.value.trim() !== '');
            paramNextBtn.disabled = !allFilled;
            paramNextBtn.style.backgroundColor = allFilled ? '#2ecc71' : '#95a5a6';
            return allFilled;
        }

        function notifyParentToStep(step, action) {
            try {
                window.parent.postMessage({
                    type: 'proceed_to_step',
                    step: step,
                    action: action
                }, '*');
            } catch (e) {
                console.error('通知父页面失败:', e);
            }
        }

       async function resetUploadState() {
            if (selectedFile) {
                try {
                    // 发送删除文件请求
                    const deleteData = {
                    type: 'reupload_file',
                    filename: selectedFile.name
                };
                    socket.send(JSON.stringify(deleteData));

                } catch (e) {
                console.error('删除文件失败:', e);
                addSystemMessage('删除旧文件失败: ' + e.message);
            }
             paramInput1.value = '20';
             paramInput2.value = '0.3';
             paramInput3.value = '20';
             paramInput4.value = '0.0005';
        }

    // 重置前端状态
    selectedFile = null;
    fileInput.value = '';
    uploadBtnText.textContent = '上传训练文件';
    uploadBtnIcons.style.display = 'none';
    nextBtn.style.display = 'none';
    reuploadBtn.style.display = 'none';
    parameterContainer.style.display = 'none';
    paramNextBtn.disabled = true;
    paramNextBtn.style.backgroundColor = '#95a5a6';
    paramNextBtn.textContent = '下一步';

    // 重置参数输入
    paramInputs.forEach(input => {
        input.value = '';
    });

    addSystemMessage('请重新上传文件');

    // 通知父页面返回步骤一
    notifyParentToStep(1, 'reupload_file');
}

        // 文件上传处理
        function uploadFile() {
            if (!selectedFile) {
                addSystemMessage('请先选择文件');
                return;
            }

            // 检查文件类型
            if (!selectedFile.name.toLowerCase().endsWith('.csv')) {
                addSystemMessage('请上传CSV格式文件');
                return;
            }
            console.log('开始上传文件:', selectedFile.name, '大小:', selectedFile.size);

            const reader = new FileReader();

            reader.onload = function(e) {
                console.log('文件读取完成，内容长度:', e.target.result.length);

                const fileData = {
                    type: 'file_upload',
                    name: selectedFile.name,
                    content: e.target.result
                };

                try {
                    socket.send(JSON.stringify(fileData));
                    console.log('文件数据已发送');
                    nextBtn.style.display = 'block';
                    reuploadBtn.style.display = 'block';
                    uploadBtnIcons.style.display = 'none';
                } catch (err) {
                    console.error('发送失败:', err);
                    addSystemMessage('文件发送失败: ' + err.message);
                }
            };

            reader.onerror = function() {
                console.error('文件读取错误');
                addSystemMessage('文件读取失败');
            };

            reader.readAsText(selectedFile);
            if (上传成功) {
                reuploadBtn.style.display = 'block';
                nextBtn.style.display = 'block';
            }
        }

        // 事件监听
        uploadBtn.addEventListener('click', function() {
            if (!selectedFile) {
                fileInput.click();
            }
            // 如果已选择文件，点击按钮本身不做任何操作
        });

        fileInput.addEventListener('change', function() {
            if (this.files && this.files.length > 0) {
                selectedFile = this.files[0];
                uploadBtnText.textContent = selectedFile.name;
                uploadBtnIcons.style.display = 'flex';
                addSystemMessage(`已选择文件: ${selectedFile.name}`);
            }
        });

        sendIcon.addEventListener('click', function(e) {
            e.stopPropagation();
            uploadFile();
        });

        trashIcon.addEventListener('click', function(e) {
            e.stopPropagation();
            selectedFile = null;
            fileInput.value = '';
            uploadBtnText.textContent = '上传训练文件';
            uploadBtnIcons.style.display = 'none';
            addSystemMessage('已取消文件选择');
        });

         nextBtn.addEventListener('click', function() {
        // 设置默认参数值
        paramInput1.value = '20';
        paramInput2.value = '0.3';
        paramInput3.value = '20';
        paramInput4.value = '0.0005';

        parameterContainer.style.display = 'block';
        nextBtn.style.display = 'none';
        checkParametersFilled();  // 立即验证默认值是否有效
        notifyParentToStep(2, 'file_uploaded');
        paramInput1.focus();
    });

        // 重新上传按钮点击事件
        reuploadBtn.addEventListener('click', function() {
            resetUploadState();
            notifyParentToStep(1, 'reupload_file');
        });

        paramInputs.forEach(input => {
            input.addEventListener('input', checkParametersFilled);
        });

        // 参数提交按钮点击事件
        paramNextBtn.addEventListener('click', function() {
            if (!checkParametersFilled()) {
                addSystemMessage('请填写所有参数');
                return;
            }

            const parameters = {
                type: 'parameters',
                epochs: paramInput1.value.trim(),
                batch_size_ratio: paramInput2.value.trim(),
                squence_len: paramInput3.value.trim(),
                learning_rate: paramInput4.value.trim() // 添加学习率参数
            };


            socket.send(JSON.stringify(parameters));
            trainResultSocket.send(JSON.stringify(parameters));
            console.log('参数已发送:', parameters);

            // 禁用按钮并改变样式
            paramNextBtn.disabled = true;
            paramNextBtn.style.backgroundColor = '#95a5a6';
            paramNextBtn.textContent = '参数已提交';

            // 隐藏重新上传按钮
            reuploadBtn.style.display = 'none';

            notifyParentToStep(3, 'parameters_submitted');
        });

        // 监听父页面消息
        window.addEventListener('message', function(event) {
            if (event.data && event.data.type === 'proceed_to_step' && event.data.step === 3) {
                paramNextBtn.disabled = true;
                paramNextBtn.style.backgroundColor = '#95a5a6';
                paramNextBtn.textContent = '参数已提交';
                reuploadBtn.style.display = 'none';
            }
        });

        // 初始化
        paramNextBtn.disabled = true;
        paramNextBtn.style.backgroundColor = '#95a5a6';
    });
</script>
</body>
</html>